package com.brayan.webapp.service.general.currencyconversion;

import java.util.HashMap;
import java.util.Map;

import javax.ejb.Singleton;

import org.joda.time.LocalDate;

@Singleton
public class CurrencyBean {
	/**
	 * Cached values of conversion rates.
	 */
	Map<Currency, Double> cachedConversionRates = new HashMap<Currency, Double>();
	LocalDate lastUpdate = null;
	
	/**
	 * Returns a cached version of the conversion Rate and fetches only from only source, if older than one day.
	 * @param currency
	 * @param targetCurrency
	 * @return
	 */
	public double getConversionRate(String currency, String targetCurrency) {
		
		Double conversionRate = cachedConversionRates.get(Currency.fromValue(targetCurrency));
		if(conversionRate == null|| conversionRate == 0 || lastUpdate.isBefore(new LocalDate()))
			conversionRate = getOnlineConversion(Currency.fromValue(currency), Currency.fromValue(targetCurrency));
		
		return conversionRate;
	}
	
	public Double getOnlineConversion (Currency srcCurrency, Currency targetCurrency){
		CurrencyConvertor curService = new CurrencyConvertor();
		CurrencyConvertorSoap soapRequest = curService
				.getCurrencyConvertorSoap();

		Double conversionRate = soapRequest.conversionRate(srcCurrency, targetCurrency);
		if(conversionRate != null && conversionRate != 0){
			cachedConversionRates.put(targetCurrency, conversionRate);
			lastUpdate = new LocalDate();
		}
		return conversionRate;
	}
	
}
